

#include "stdafx.h"
#include <QHash>
#include "pf_fontlist.h"
#include "pf_debug.h"
#include "pf_font.h"
#include "pf_system.h"

PF_FontList* PF_FontList::uniqueInstance = NULL;



/**
 * Default constructor.
 */
PF_FontList::PF_FontList() {
}



/**
 * Initializes the font list by creating empty PF_Font 
 * objects, one for each font that could be found.
 */
void PF_FontList::init() {
    PF_DEBUG->print("PF_FontList::initFonts");

    QStringList list = PF_SYSTEM->getFontList();
    QHash<QString, int> added; //used to remember added fonts (avoid duplication)
    PF_Font* font;

    for (int i = 0; i < list.size(); ++i) {
        PF_DEBUG->print("font: %s:", list.at(i).toLatin1().data());

        QFileInfo fi( list.at(i) );
        if ( !added.contains(fi.baseName()) ) {
            font = new PF_Font(fi.baseName());
            fonts.append(font);
            added.insert(fi.baseName(), 1);
        }

        PF_DEBUG->print("base: %s", fi.baseName().toLatin1().data());
    }
}



/**
 * Removes all fonts in the fontlist.
 */
void PF_FontList::clearFonts() {
    while (!fonts.isEmpty())
        delete fonts.takeFirst();
}



/**
 * Removes a font from the list.
 * The font was removed from the list and is deleted.
 */
void PF_FontList::removeFont(PF_Font* font) {
    PF_DEBUG->print("PF_FontList::removeFont()");

    int i = fonts.indexOf(font);
    if (i != -1)
        delete fonts.takeAt(i);

    //for (uint i=0; i<fontListListeners.count(); ++i) {
    //    PF_FontListListener* l = fontListListeners.at(i);
    //    l->fontRemoved(font);
    //}
}



/**
 * @return Pointer to the font with the given name or
 * \p NULL if no such font was found. The font will be loaded into
 * memory if it's not already.
 */
PF_Font* PF_FontList::requestFont(const QString& name) {
    PF_DEBUG->print("PF_FontList::requestFont %s",  name.toLatin1().data());

    QString name2 = name.toLower();
    PF_Font* foundFont = NULL;

    if (name2.contains('#') && name2.contains('_')) {
        name2 = name2.left(name2.indexOf('_'));
    } else if (name2.contains('#')) {
        name2 = name2.left(name2.indexOf('#'));
    }

    PF_DEBUG->print("name2: %s", name2.toLatin1().data());

    // Search our list of available fonts:
    for (int i = 0; i < fonts.size(); ++i) {
        PF_Font* f = fonts.at(i);

        if (f->getFileName()==name2) {
            // Make sure this font is loaded into memory:
            f->loadFont();
            foundFont = f;
            break;
        }
    }

    if (foundFont==NULL && name!="standard") {
        foundFont = requestFont("standard");
    }

    return foundFont;
}



/**
 * Dumps the fonts to stdout.
 */
std::ostream& operator << (std::ostream& os, PF_FontList& l) {

    os << "Fontlist: \n";
    for (int i = 0; i < l.fonts.size(); ++i) {
        PF_Font* f = l.fonts.at(i);

        os << *f << "\n";
    }

    return os;
}




